package com.project.servlet;

import com.project.bean.ProductBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //将表单数据封装成商品对象
        ProductBean product = new ProductBean();

//        product.setName(req.getParameter("name"));
//        product.setPrice(Integer.parseInt(req.getParameter("price")));
//        product.setStartDate(LocalDate.parse(req.getParameter("startDate")));
//        product.setFactory(req.getParameter("factory"));

        fullBean(product,req);
        resp.getWriter().print(product);

    }

    private void fullBean(Object beanObj, HttpServletRequest req) {

        Enumeration<String> em = req.getParameterNames();//得到该表单所有的表单名

        while (em.hasMoreElements()){//判断是否有更多的元素（相当于next（））
            try {
            //有就取出下一个元素
            String str = em.nextElement();//表单名
//            System.out.println(str);

            //根据表单名得到实体类的属性对象

                Field f = beanObj.getClass().getDeclaredField(str);
                f.setAccessible(true);

                String value = req.getParameter(str);//根据表单名得到表单值

                if (f.getType() == String.class){
                    f.set(beanObj,value);
                }
                else if (f.getType() == int.class || f.getType() == Integer.class){
                    f.set(beanObj,Integer.parseInt(value));
                }
                else if (f.getType() == double.class || f.getType() == Double.class){
                    f.set(beanObj,Double.parseDouble(value));
                }
                else if (f.getType() == LocalDate.class){
                    f.set(beanObj,LocalDate.parse(value));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
